package city.spring.modules.system.controller;

import city.spring.modules.system.entity.DataDictionaryEntity;
import city.spring.modules.system.entity.DataDictionaryValueEntity;
import city.spring.modules.system.service.DataDictionaryService;
import city.spring.modules.system.service.DataDictionaryValueService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.google.common.collect.ArrayListMultimap;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据字典值信息 控制器
 *
 * @author HouKunLin
 * @date 2020/3/26 0026 23:40
 */
@RestController
@RequestMapping("/dataDictionary")
public class DataDictionaryApiController extends ApiController {
    private final DataDictionaryService dataDictionaryService;
    /**
     * <strong>数据字典值信息</strong> Service
     */
    private final DataDictionaryValueService dataDictionaryValueService;
    /**
     * 实体类（数据字典值信息）可排序字段
     */
    private final List<SFunction<DataDictionaryValueEntity, ?>> entityOrderFields;

    public DataDictionaryApiController(DataDictionaryService dataDictionaryService, DataDictionaryValueService dataDictionaryValueService) {
        this.dataDictionaryService = dataDictionaryService;
        this.dataDictionaryValueService = dataDictionaryValueService;
        this.entityOrderFields = new ArrayList<>();
        this.entityOrderFields.add(DataDictionaryValueEntity::getId);
        this.entityOrderFields.add(DataDictionaryValueEntity::getDictionaryId);
        this.entityOrderFields.add(DataDictionaryValueEntity::getLabel);
        this.entityOrderFields.add(DataDictionaryValueEntity::getValue);
        this.entityOrderFields.add(DataDictionaryValueEntity::getEnabled);
        this.entityOrderFields.add(DataDictionaryValueEntity::getSorted);
        this.entityOrderFields.add(DataDictionaryValueEntity::getGmtCreate);
        this.entityOrderFields.add(DataDictionaryValueEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>数据字典值信息</strong> 列表
     */
    @GetMapping("getAllDict")
    public Object getAllDict() {
        List<DataDictionaryEntity> dictionaryEntities = dataDictionaryService.list();
        List<DataDictionaryValueEntity> valueEntities = dataDictionaryValueService.list();

        ArrayListMultimap<String, DataDictionaryValueEntity> multimap = ArrayListMultimap.create();
        valueEntities.forEach(dataDictionaryValueEntity -> multimap.put(dataDictionaryValueEntity.getDictionaryId(), dataDictionaryValueEntity));
        dictionaryEntities.forEach(dataDictionaryEntity ->
                dataDictionaryEntity.setChildren(multimap.get(dataDictionaryEntity.getId())));


        return success(dictionaryEntities);
    }

    /**
     * 获取全部的 <strong>数据字典值信息</strong> 列表
     */
    @GetMapping("dict-{dictionaryType}")
    public Object listValues(@PageableDefault Pageable pageable, DataDictionaryValueEntity entity, @PathVariable String dictionaryType) {
        return success(loadDataDictionaryEntity(pageable, entity, dictionaryType).getChildren());
    }

    /**
     * 获取全部的 <strong>数据字典值信息</strong> 列表，同时包含数据字典信息一起返回
     */
    @GetMapping(value = "dict-{dictionaryType}", params = {"loadDictType=true"})
    public Object listTypeAndChildren(@PageableDefault Pageable pageable, DataDictionaryValueEntity entity, @PathVariable String dictionaryType) {
        return success(loadDataDictionaryEntity(pageable, entity, dictionaryType));
    }

    @NonNull
    private DataDictionaryEntity loadDataDictionaryEntity(Pageable pageable, DataDictionaryValueEntity entity, String dictionaryType) {
        DataDictionaryEntity result;

        // 从数据库查找字典类型
        List<DataDictionaryEntity> dataDictionaryEntities = dataDictionaryService.lambdaQuery()
                .eq(DataDictionaryEntity::getType, dictionaryType)
                .or()
                .eq(DataDictionaryEntity::getId, dictionaryType)
                .list();

        // 判断查找结果是否为空
        if (dataDictionaryEntities.isEmpty()) {
            result = new DataDictionaryEntity();
            result.setTitle("未知字典类型");
            result.setChildren(Collections.emptyList());
            return result;
        }

        // 查找字典值列表信息
        LambdaQueryChainWrapper<DataDictionaryValueEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        if (dataDictionaryEntities.size() == 1) {
            result = dataDictionaryEntities.get(0);
            lambdaQuery.eq(DataDictionaryValueEntity::getDictionaryId, result.getId());
        } else {
            result = dataDictionaryEntities.get(0);
            List<String> stringList = dataDictionaryEntities.stream()
                    .map(DataDictionaryEntity::getId)
                    .collect(Collectors.toList());
            lambdaQuery.in(DataDictionaryValueEntity::getDictionaryId, stringList);
        }
        result.setChildren(lambdaQuery.list());
        return result;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象： <strong>数据字典值信息</strong>
     * @return lambda query chain wrapper
     */
    @NonNull
    private LambdaQueryChainWrapper<DataDictionaryValueEntity> buildLambdaQuery(DataDictionaryValueEntity entity) {
        LambdaQueryChainWrapper<DataDictionaryValueEntity> lambdaQuery = dataDictionaryValueService.lambdaQuery();
        lambdaQuery.eq(entity.getEnabled() != null, DataDictionaryValueEntity::getEnabled, entity.getEnabled());
        return lambdaQuery;
    }
}
